package com.czy.service.impl;

import com.czy.dto.UserDto;
import com.czy.dto.UserPageDto;
import com.czy.mapper.AssetMapper;
import com.czy.mapper.BorrowRecordMapper;
import com.czy.mapper.UserMapper;
import com.czy.service.UserService;
import com.czy.dto.LoginDto;
import com.czy.entity.User;
import com.czy.exception.SystemException;
import com.czy.utils.BCryptPasswordUtils;
import com.czy.utils.BeanCopyUtils;
import com.czy.utils.JwtUtils;
import com.czy.utils.ThreadLocalUtils;
import com.czy.vo.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AssetMapper assetMapper;

    @Autowired
    private BorrowRecordMapper borrowRecordMapper;

    // 查询用户全部信息
    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }


    /**
     * 登录
     *
     * @param loginDto 用户名和密码
     * @return 登录成功后响应的数据
     */
    @Override
    public LoginVo login(LoginDto loginDto) {

        User user = userMapper.selectByUsernameAndPassword(loginDto);
        LoginVo vo = new LoginVo();

        //用户存在，并且密码正确，生产jwt令牌
        if (user != null && BCryptPasswordUtils.checkPassword(loginDto.getPassword(),user.getPassword())) {
            // 创建自定义信息
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", user.getId());
            claims.put("username", user.getPassword());
            String token = JwtUtils.createToken(claims);

            //封装jwt令牌
            vo.setToken(token);

        } else {
            throw new SystemException(405, "用户名或密码错误");
        }
        return vo;
    }

    /**
     * 获取用户信息
     */
    @Override
    public UserInfoVo info() {
        //获取用户当前Id
        Integer currentId = ThreadLocalUtils.getCurrentId();

        //调用sql进行查询
        UserInfoVo vo = userMapper.LoginFindById(currentId);

        //返回
        return vo;
    }

    /**
     * 获取资产总数据
     */
    @Override
    public AssetsTotalVo getAssets() {

        //获取资产总数
        Integer assetSum = assetMapper.assetSum();

        //获取借出资产数量
        Integer borrowRecordSum = borrowRecordMapper.borrowRecordSum();

        //可用资产数量
        Integer availableSum = assetSum - borrowRecordSum;

        AssetsTotalVo vo = new AssetsTotalVo(assetSum, availableSum, borrowRecordSum);

        return vo;
    }

    /**
     * 获取最近的借用记录数
     */
    @Override
    public List<BorrowRecordInfoVo> BorrowRecordInfo() {
        List<BorrowRecordInfoVo> vo = borrowRecordMapper.loanRecords();
        return vo;
    }

    /**
     * 分页查询用户数据
     */
    @Override
    public PageVo page(UserPageDto pageDto) {
        //设置分页
        PageHelper.startPage(pageDto.getPageNum(), pageDto.getPageSize());

        //执行查询
        List<User> userList = userMapper.list(pageDto);

        Page<User> userPage = (Page<User>) userList;

        return new PageVo(userPage.getTotal(),userPage.getResult());
    }

    /**
     * 新增用户信息
     */
    @Override
    public void add(UserDto userDto) {

        //添加时，未写密码或密码长度不够时使用默认的
        if(userDto.getPassword().isEmpty() || userDto.getPassword().length() < 6){
            userDto.setPassword(BCryptPasswordUtils.encryptedPasswords("123456"));
        }else {
            //对写了的密码进行加密
            String password = BCryptPasswordUtils.encryptedPasswords(userDto.getPassword());
            userDto.setPassword(password);
        }

        //拷贝
        User user = BeanCopyUtils.copyBean(userDto, User.class);


        System.out.println(user);

        //补全基础属性，创建时间和修改时间
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        userMapper.insertUser(user);
    }

    /**
     * 根据id修改用户
     */
    @Override
    public void update(UserDto userDto) {

        User user = BeanCopyUtils.copyBean(userDto, User.class);

        // 密码不为空，进行加密处理
        if (userDto.getPassword() != null || !(userDto.getPassword().isEmpty())){
            String newPassword = BCryptPasswordUtils.encryptedPasswords(userDto.getPassword());
            user.setPassword(newPassword);
        }

        System.out.println(user);

        //补全基础属性，修改时间
        user.setUpdateTime(LocalDateTime.now());

        //获取修改员工ID
        user.setId(Long.valueOf(userDto.getId()));


        userMapper.updateUser(user);
    }

    /**
     * 批量删除用户
     */
    @Override
    public void deleteByIdUser(List<Integer> ids) {
        userMapper.deleteByIds(ids);
    }

    /**
     * 根据ID查询用户(查询回显)
     */
    @Override
    public UserVo findById(Integer id) {
        return userMapper.selectById(id);
    }
}
